﻿
CREATE PROCEDURE [dbo].[GetNextCounterFor] (
	@CounterName varchar(20),
	@Next int OUTPUT
)
AS
BEGIN
SET NOCOUNT ON;

DECLARE @intTrancount int, @intDepartmentId int

SET @intTrancount = @@TRANCOUNT

IF @intTrancount <=0 
	BEGIN TRAN
ELSE 
	SAVE TRAN NextCounter

IF @CounterName = 'Common'
BEGIN 
	INSERT INTO PR.CounterCommon(FixedVal) VALUES(DEFAULT)
	GOTO DOCOUNTER
END

IF @CounterName = 'Documents'
BEGIN 
	INSERT INTO PR.CounterDocuments(FixedVal) VALUES(DEFAULT)
	GOTO DOCOUNTER
END

IF @CounterName = 'GoodsLines'
BEGIN 
	INSERT INTO PR.CounterGoodsLines(FixedVal) VALUES(DEFAULT)
	GOTO DOCOUNTER
END

DOCOUNTER:

--select IDENT_CURRENT( 'PR.CommonSequence' )
--truncate table PR.CommonSequence -- сбрасывает IDENTITY в начальные значения
--DBCC CHECKIDENT ('PR.CommonSequence', RESEED, 30) -- новое значение IDENTITY
SELECT @intDepartmentId = DepartmentId FROM PR.DepartmentOptions WITH (NOLOCK)
-- 0x5f5e100  = 100000000
SET @Next = SCOPE_IDENTITY() + @intDepartmentId * 100000000 --cast(0x5f5e100 as int)

IF @intTrancount <=0 
	ROLLBACK TRAN
ELSE 
	ROLLBACK TRAN NextCounter

RETURN 0
END
